package com.cmpe451.nutty.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import com.cmpe451.nutty.model.User;
import com.cmpe451.nutty.service.UserService;
import com.cmpe451.nutty.so.GuiUser;
import com.cmpe451.nutty.utils.LoginUtils;

public class UserAuthenticationProvider implements AuthenticationProvider {
	private UserService userDetailsService;

	@Autowired
	private LoginUtils loginUtils;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		if (authentication.getCredentials() == null) {
			throw new BadCredentialsException("error.user.badCredentials");
		}

		GuiUser user = null;
		try {
			user = (GuiUser) userDetailsService.loadUserByUsername(authentication.getName());
			if( user == null)
				return null;
		} catch (Exception e) {
			//throw new BadCredentialsException("error.user.notFound");
			
		}

		User validUser = userDetailsService.getUserById(user.getId());
		
		String passwordEntered = authentication.getCredentials().toString();
		if (!user.getPassword().equals(passwordEntered) || validUser.getValid() != 1) {
			throw new BadCredentialsException("error.user.invalidPassword");
		}
		
		UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), user.getAuthorities());
		result.setDetails(user);

		return result;
	}

	@Override
	public boolean supports(Class<?> class1) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(class1);
	}

	public void setUserDetailsService(UserService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

}
